import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/branch_detail_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_branch_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_branch/show_branch_address_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/binding_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/show_terminal_address_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_pic_detail_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/set_terminal_state_type.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_terminal_status_menu_dialog.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'company_branch_detail_view_model.dart';
import 'company_create_or_edit_branch_page.dart';

class CompanyBranchDetailPage extends StatefulWidget {

  static const String ROUTER = "CompanyBranchDetailPage";

  final CompanyBranchListInfoBean infoBean;
  final int size;
  const CompanyBranchDetailPage({Key key, this.infoBean, this.size}) : super(key: key);

  @override
  _CompanyBranchDetailPageState createState() => _CompanyBranchDetailPageState();

  static Future<dynamic> navigatorPush(BuildContext context,
      CompanyBranchListInfoBean infoBean, int size) {
    return RouterUtils.routeForFutureResult(
      context,
      CompanyBranchDetailPage(
        infoBean: infoBean,
        size: size,
      ),
      routeName: CompanyBranchDetailPage.ROUTER,
    );
  }

}

class _CompanyBranchDetailPageState
    extends BaseState<CompanyBranchDetailPage> {

  CompanyBranchDetailViewModel _branchDetailViewModel;

  CommonListPageWidgetState mState;

  BranchDetailDataBean _data;
  NewTerminalListViewModel _viewModel;
  CompanyBranchListInfoBean _infoBean;

  @override
  void initState() {
    super.initState();
    _infoBean = widget?.infoBean;
    _viewModel = NewTerminalListViewModel(this);
    _data = BranchDetailDataBean();
    _branchDetailViewModel = CompanyBranchDetailViewModel(this);
    _initDate();
    _branchDetailViewModel?.getBasicInfoCache();
    VgEventBus.global.on<RefreshBranchDetailEvent>().listen((event) {
      _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
    });
  }
  _initDate(){
    _branchDetailViewModel?.groupInfoComBranch?.addListener(() {
      setState(() {
        if (_branchDetailViewModel.groupInfoComBranch.value != null) {
          _data = _branchDetailViewModel?.groupInfoComBranch?.value;
        }
      });
    });
    _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          children: [
            _toTopBarWidget(),
            _toCompanyBranchItemWidget(),
            _toMachineCntWidget(),
            _toMainContentWidget(),
          ],
        ),
      ),
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      title: "地址详情",
      isShowBack: true,
      rightWidget:  GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: ()async{
          CompanyCreateOrEditBranchPage.navigatorPush(context,"编辑", _infoBean, _infoBean?.gps,"", (){
            _branchDetailViewModel.removeCompanyBranch(context, _infoBean?.cbid);
          }, updateBranch: (infobean){
            setState(() {
              _infoBean = infobean;
            });
          }, size: widget?.size).then((value) => mState?.viewModel?.refresh());
        },
        child: Visibility(
          visible: AppOverallDistinguish.comefromAiOrWeStudy(),
          child: Container(
            padding: EdgeInsets.only(top: 8, left: 8, bottom: 8),
            child: Text(
              "编辑",
              style: TextStyle(
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                fontSize: 14,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _toCompanyBranchItemWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: EdgeInsets.symmetric(horizontal: 15,vertical: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            alignment: Alignment.centerLeft,
            child: Text(
              "${_data?.ComBranch?.branchname}",
              style: TextStyle(
                fontSize: 17,
                color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
              ),
            ),
          ),
          SizedBox(height: 2),
          Row(
            children: [
              Expanded(
                child: Text(
                  _branchAddressStr(_data?.ComBranch),
                  style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                  ),
                ),
              ),
              Visibility(
                visible: (_data?.ComBranch?.gps != null || _data?.ComBranch?.gps != ""),
                child: Container(
                  width: 1,
                  height: 25,
                  color: Color(0xFF303546),
                  margin: EdgeInsets.symmetric(horizontal: 15),
                ),
              ),
              Visibility(
                visible: (_data?.ComBranch?.gps != null || _data?.ComBranch?.gps != ""),
                child: GestureDetector(
                  onTap: (){
                    if(StringUtils.isNotEmpty((_data?.ComBranch?.gps ?? ""))){
                      ShowBranchAddressPage.navigatorPush(context, _data?.ComBranch);
                    }else{
                      VgToastUtils.toast(context, "gps位置信息异常");
                    }
                  },
                  child: Image.asset(
                    "images/branch_detail_gps_ico.png",
                    height: 24,
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }

  Widget _toMachineCntWidget(){
    return Container(
      height: 30,
      color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      child: Row(
        children: [
          Container(
            padding: EdgeInsets.only(top: 7, left: 14, bottom: 6),
            child: Text(
              "关联${_data?.allCnt}设备/",
              style: TextStyle(
                fontSize: 12,
                color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
              ),
            ),
          ),
          Text(
            "开机${_data?.powerOnCnt}",
            style: TextStyle(
              fontSize: 12,
              color: ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _toMainContentWidget(){
    return Expanded(
      child: ValueListenableBuilder(
          valueListenable: _branchDetailViewModel?.statusTypeValueNotifier,
          builder:
              (BuildContext context, PlaceHolderStatusType value, Widget child) {
            return VgPlaceHolderStatusWidget(
              loadingStatus: value == PlaceHolderStatusType.loading,
              errorStatus: value == PlaceHolderStatusType.error,
              errorOnClick: () => _branchDetailViewModel
                  .branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps),
              loadingOnClick: () => _branchDetailViewModel
                  .branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps),
              child: child,
            );
          },
        child: _toListWidget()),
    );
  }

  Widget _toListWidget(){
    return ListView.separated(
      itemCount: _data?.page?.records?.length ?? 0,
      padding: const EdgeInsets.all(0),
      physics: BouncingScrollPhysics(),
      keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
      itemBuilder: (BuildContext context, int index) {
        return _toListItemWidget(context, index, _data?.page?.records?.elementAt(index));
      },
      separatorBuilder: (BuildContext context, int index){
        return SizedBox(height: 0);
      },
    );
  }

  Widget _toListItemWidget(BuildContext context, int index, CompanyBranchDetailListItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        TerminalDetailInfoPage.navigatorPush(context, itemBean?.hsn, terminalCount: _data?.page?.records?.length ?? 0, router: CompanyBranchDetailPage.ROUTER);
      },
      child: Container(
        height: 102,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 78,
                  height: 78,
                  color: Color(0xFF191E31),
                  child: VgCacheNetWorkImage(
                    itemBean?.terminalPicurl ?? "",
                    defaultErrorType: ImageErrorType.head,
                    errorWidget: Container(
                      child: Image.asset(
                        "images/icon_terminal_holder.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                    placeWidget: Container(
                      child: Image.asset(
                        "images/termial_empty_place_holder_ico.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                )),
            Expanded(child: _toContentWidget(context, index, itemBean)),
            // _toButtonStatusWidget(itemBean),
          ],
        ),
      ),
    );
  }

  void _onOpen(SetTerminalStateType currentState, String hsn){
    print("开机");
    _viewModel.terminalOffScreen(context, hsn, "00", callback: (){
      _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
    });
  }

  void _screenOff(SetTerminalStateType currentState, String hsn){
    print("息屏开机");
    _viewModel.terminalOffScreen(context, hsn, "01", callback: (){
      _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
    });
  }

  void _off(SetTerminalStateType currentState, String hsn){
    print("关机");
    _viewModel.terminalOff(context, hsn, callback: (){
      _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
    });
  }

  Widget _toContentWidget(context, int index, CompanyBranchDetailListItemBean itemBean) {
    SetTerminalStateType currentType = itemBean.getTerminalState();
    return Container(
      margin: const EdgeInsets.only(left: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                width: 160,
                child: Text(
                  itemBean.getTerminalName(index),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Spacer(),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: (){
                  SetTerminalStatusMenuDialog.navigatorPushDialog(context,
                        (currentState){
                      _onOpen?.call(currentState, itemBean?.hsn);
                    },
                        (currentState){
                      _screenOff?.call(currentState, itemBean?.hsn);
                    },
                        (currentState){
                      _off?.call(currentState, itemBean?.hsn);
                    },
                        (time){
                          if(StringUtils.isNotEmpty(time)){
                            _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
                          }
                    },
                    itemBean?.getTerminalState(),
                    itemBean?.autoOnoffTime??"",
                    itemBean?.autoOnoffWeek??"",
                    itemBean.hsn,
                    itemBean.id,
                    itemBean?.getTerminalName(index),
                    itemBean?.autoOnoff,
                    itemBean?.comAutoSwitch,
                      weekChange: (week){
                        setState(() {
                          if(StringUtils.isNotEmpty(week)){
                            _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
                          }
                        });
                      },
                      autoOnOffChange: (onOff){
                        setState(() {
                          _branchDetailViewModel.branchTerminalDetailInfo(context, _infoBean?.cbid, _infoBean?.gps);
                        });
                      }
                  );
                },
                child: Container(
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    children: [
                      // SizedBox(width: 20,),
                      Container(
                        alignment: Alignment.centerRight,
                        // width: 80,
                        padding: EdgeInsets.symmetric(vertical: 2.5),
                        child: Text(
                          itemBean.getTerminalStateString(),
                          style: TextStyle(
                            fontSize: 12,
                            color: (itemBean?.getTerminalIsOff()??true)
                                ?ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C()
                                :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                          ),
                        ),
                      ),
                      Visibility(
                        visible: !(itemBean?.getTerminalIsOff()??true),
                        child: Row(
                          children: [
                            SizedBox(width: 5,),
                            Image(
                              image: AssetImage("images/icon_shape_arrow_down.png"),
                              width: 7,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 2,
          ),
          Container(
            margin: const EdgeInsets.only(right: 12),
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 2,
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}（${(itemBean?.loginName) ?? ""}账号登录）",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          ),
          SizedBox(
            height: 3,
          ),
          _toAccountStatus(itemBean),
        ],
      ),
    );
  }

  Widget _toAccountStatus(CompanyBranchDetailListItemBean itemBean){
    return Row(
      children: [
        Text(
          "账号状态：",
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              height: 1.22
          ),
        ),
        Text(
          itemBean.getEndDayString(),
          style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              height: 1.2
          ),
        ),
        Text(
          itemBean.getNotifyString(),
          style: TextStyle(
              color: ThemeRepository.getInstance().getMinorRedColor_F95355(),
              fontSize: 12,
              height: 1.2
          ),
        ),
      ],
    );
  }

  String _branchAddressStr(ComBranchBean itemBean){
    String addressStr = itemBean?.address;
    if(itemBean?.addrProvince == itemBean?.addrCity){
      addressStr = "${itemBean?.addrProvince}${itemBean?.addrDistrict}·${itemBean?.address}";
    }else{
      addressStr = "${itemBean?.addrProvince}${itemBean?.addrCity}${itemBean?.addrDistrict}·${itemBean?.address}";
    }
    return addressStr;
  }
}
